<template>
	<view style="position: relative;">
		<view class="verifyimg">
			<image :src="backImgBase ? 'data:image/png;base64,' + backImgBase : defaultImg"></image>
		</view>
		<view class="verify-bar-area">
			<span class="verify-msg" v-text="text"></span>
			<view class="verify-left-bar" @touchstart="start" @touchmove="move" @touchend="end" :style="{
          width:'50px',
          height: '50px',
          'border-color': leftBarBorderColor,
          transaction: transitionWidth,
		  left: moveBlockLeft
        }">
				<uv-icon class="verify-left-bar_icon" :name="iconClass"
					:style="{ color: iconColor,'line-height':'100rpx', }" size="18"></uv-icon>
				<view class="verify-sub-block">
					<image :src="'data:image/png;base64,' + blockBackImgBase" alt="" />
				</view>
			</view>
		</view>
	</view>
</template>
<script type="text/babel">
	/**
 * VerifySlide
 * @description 滑块
 * */
import { aesEncrypt } from "./../utils/ase";
import { resetSize } from "./../utils/util";	
import api from '@/api'

//  "captchaType":"blockPuzzle",
export default {
  name: "VerifySlide",
  props: {
    captchaType: {
      type: String,
    },
    type: {
      type: String,
      default: "1",
    },
    //弹出式pop，固定fixed
    mode: {
      type: String,
      default: "fixed",
    },
    vSpace: {
      type: Number,
      default: 5,
    },
    explain: {
      type: String,
      default: "向右滑动完成验证",
    },
    imgSize: {
      type: Object,
      default() {
        return {
          width: "310px",
          height: "155px",
        };
      },
    },
    blockSize: {
      type: Object,
      default() {
        return {
          width: "50px",
          height: "50px",
        };
      },
    },
    barSize: {
      type: Object,
      default() {
        return {
          width: "310px",
          height: "40px",
        };
      },
    },
    defaultImg: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      secretKey: "", //后端返回的加密秘钥 字段
      passFlag: "", //是否通过的标识
      backImgBase: "", //验证码背景图片
      blockBackImgBase: "", //验证滑块的背景图片
      backToken: "", //后端返回的唯一token值
      startMoveTime: "", //移动开始的时间
      endMovetime: "", //移动结束的时间
      tipsBackColor: "", //提示词的背景颜色
      tipWords: "",
      text: "",
      finishText: "",
      setSize: {
        imgHeight: 0,
        imgWidth: 0,
        barHeight: 0,
        barWidth: 0,
      },
      top: 0,
      left: 0,
      moveBlockLeft: undefined,
      leftBarWidth: undefined,
      // 移动中样式
      moveBlockBackgroundColor: undefined,
      leftBarBorderColor: "#ddd",
      iconColor: undefined,
      iconClass: "arrow-right",
      status: false, //鼠标状态
      isEnd: false, //是够验证完成
      showRefresh: true,
      transitionLeft: "",
      transitionWidth: "",
    };
  },
  methods: {
    init() {
      this.text = this.explain;
      this.getPictrue();
      this.$nextTick(() => {
        this.$parent.$emit("ready", this);
      });
    },

    //鼠标按下
    start: function (e) {
		const _this = this
      let x = e.touches[0].pageX;
	  const query = uni.createSelectorQuery().in(this)
	  query.select(".verify-bar-area").boundingClientRect(data => {
	    _this.startLeft = Math.floor(
	      x - data.left
	    );
		_this.setSize = {
			imgWidth: data.width,
			barHeight: data.height,
			barWidth: data.height,
		}
	  }).exec();
      this.startMoveTime = +new Date(); //开始滑动的时间
      if (this.isEnd == false) {
        this.text = "";
        this.moveBlockBackgroundColor = "#337ab7";
        this.leftBarBorderColor = "#337AB7";
        this.iconColor = "#fff";
        e.stopPropagation();
        this.status = true;
      }
    },
    //鼠标移动
    move: function (e) {
	  const _this = this
      if (this.status && this.isEnd == false) {
        let x = e.touches[0].pageX;
		const query = uni.createSelectorQuery().in(this)
		query.select(".verify-bar-area").boundingClientRect(({left,width}) => {
		  let bar_area_left = left;
		  let move_block_left = x - bar_area_left; //小方块相对于父元素的left值
		  if (
		    move_block_left >=
		    width -
		      parseInt(parseInt(this.blockSize.width) / 2) -
		      2
		  ) {
		    move_block_left =
		      width -
		      parseInt(parseInt(this.blockSize.width) / 2) -
		      2;
		  }
		  if (move_block_left <= 0) {
		    move_block_left = parseInt(parseInt(this.blockSize.width) / 2);
		  }
		  //拖动后小方块的left值
		  _this.moveBlockLeft = move_block_left - _this.startLeft + "px";
		  _this.leftBarWidth = move_block_left - _this.startLeft + "px";
		}).exec();
        
      }
    },

    //鼠标松开
    end: function () {
      this.endMovetime = +new Date();
      var _this = this;
      //判断是否重合
      if (this.status && this.isEnd == false) {
        var moveLeftDistance = parseInt(
          (this.moveBlockLeft || "").replace("px", "")
        );
        moveLeftDistance =
          (moveLeftDistance * 310) / parseInt(this.setSize.imgWidth);
        let data = {
          captchaType: this.captchaType,
          pointJson: this.secretKey
            ? aesEncrypt(
                JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
                this.secretKey
              )
            : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
          token: this.backToken,
        };
        api.user.reqCheck(data).then((res) => {
          if (res.repCode == "0000") {
            this.moveBlockBackgroundColor = "#5cb85c";
            this.leftBarBorderColor = "#5cb85c";
            this.iconColor = "#fff";
            this.iconClass = "checkmark";
            this.showRefresh = false;
            this.isEnd = true;
            this.passFlag = true;
            this.tipWords = `${(
              (this.endMovetime - this.startMoveTime) /
              1000
            ).toFixed(2)}s验证成功`;
			uni.showToast({
				icon:'none',
				title: this.tipWords
			})
            var captchaVerification = this.secretKey
              ? aesEncrypt(
                  this.backToken +
                    "---" +
                    JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
                  this.secretKey
                )
              : this.backToken +
                "---" +
                JSON.stringify({ x: moveLeftDistance, y: 5.0 });
            setTimeout(() => {
              this.tipWords = "";
              this.$parent.closeBox();
              this.$parent.$emit("success", { captchaVerification });
            }, 1000);
          } else {
            this.moveBlockBackgroundColor = "#d9534f";
            this.leftBarBorderColor = "#d9534f";
            this.iconColor = "#fff";
            this.iconClass = "close";
            this.passFlag = false;
            setTimeout(function () {
              _this.refresh();
            }, 1000);
            this.$parent.$emit("error", this);
            this.tipWords = "验证失败";
			uni.showToast({
				icon:'none',
				title: this.tipWords
			})
            setTimeout(() => {
              this.tipWords = "";
            }, 1000);
          }
        });
        this.status = false;
      }
    },

    refresh: function () {
      this.showRefresh = true;
      this.finishText = "";

      this.transitionLeft = "left .3s";
      this.moveBlockLeft = 0;

      this.leftBarWidth = undefined;
      this.transitionWidth = "width .3s";

      this.leftBarBorderColor = "#ddd";
      this.moveBlockBackgroundColor = "#fff";
      this.iconColor = "#000";
      this.iconClass = "arrow-right";
      this.isEnd = false;

      this.getPictrue();
      setTimeout(() => {
        this.transitionWidth = "";
        this.transitionLeft = "";
        this.text = this.explain;
      }, 300);
    },

    // 请求背景图片和验证图片
    getPictrue() {
      let data = {
        captchaType: this.captchaType,
        clientUid: uni.getStorageSync("slider"),
        ts: Date.now(), // 现在的时间戳
      };
      api.user.reqGet(data).then((res) => {
        if (res.repCode == "0000") {
          this.backImgBase = res.repData.originalImageBase64;
          this.blockBackImgBase = res.repData.jigsawImageBase64;
          this.backToken = res.repData.token;
          this.secretKey = res.repData.secretKey;
        } else {
          this.tipWords = res.repMsg;
        }

        // 判断接口请求次数是否失效
        if (res.repCode == "6201") {
          this.backImgBase = null;
          this.blockBackImgBase = null;
        }
      });
    },
  },
  watch: {
    // type变化则全面刷新
    type: {
      immediate: true,
      handler() {
        this.init();
      },
    },
  },
  mounted() {
    // 禁止拖拽
    this.$el.onselectstart = function () {
      return false;
    };
  },
};
</script>

<style scoped lang="scss">
	.verifyimg {
		width: 100%;
		height: 312rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.verify-bar-area {
		height: 50px;
		line-height: 50px;
		width: 100%;
		position: relative;
		background: #ffffff;
		text-align: center;
		box-sizing: content-box;
		border: 1px solid #ddd;

		.verify-move-block {
			position: absolute;
			top: 0px;
			left: 0;
			background: #fff;
			cursor: pointer;
			-webkit-box-sizing: content-box;
			-moz-box-sizing: content-box;
			box-sizing: content-box;
			box-shadow: 0 0 2px #888888;
			-webkit-border-radius: 1px;

			&:hover {
				background-color: #337ab7;
				color: #ffffff;
			}
		}

		.verify-left-bar {
			position: absolute;
			top: -1px;
			left: -1px;
			background: #f0fff0;
			cursor: pointer;
			box-sizing: content-box;
			border: 1px solid #ddd;

			&_icon {
				height: 50px;
				display: flex;
				justify-content: center;
			}

		}

		.verify-sub-block {
			position: absolute;
			text-align: center;
			z-index: 3;
			width: 50px;
			height: 312rpx;
			top: -312rpx;
			background-size: 100% 312rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>